<template>
    <div class="change-password-container">
        <el-form ref="passwordForm" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm">
            <!-- 原密码 -->
            <el-form-item label="原密码" prop="oldPassword">
                <el-input v-model="form.oldPassword" type="password" placeholder="请输入原密码" show-password />
            </el-form-item>

            <!-- 新密码 -->
            <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="form.newPassword" type="password" placeholder="请输入新密码" show-password />
            </el-form-item>

            <!-- 确认新密码 -->
            <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
                <el-button type="primary" @click="onSubmit">提交</el-button>
                <el-button @click="onReset">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup>
import { ref, reactive } from "vue"
import {  useRouter } from 'vue-router'
import EventBus from '../../../utils/EventBus'
import { ElMessage } from 'element-plus';
import { changePwd } from '@/api/common/common'

const router = useRouter()
const form = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
});

// 表单校验规则
const rules = reactive({
    oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' },
    ],
    confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== form.newPassword) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur',
        },
    ],
});

// 表单引用
const passwordForm = ref(null);

// 提交表单
const onSubmit = () => {
    passwordForm.value.validate((valid) => {
        if (valid) {
            // 这里可以调用 API 提交数据
            changePwd(form).then(data => {
                ElMessage.success('密码修改成功');
                EventBus.emit('close_current_and_to_index')
            })
        } else {
            ElMessage.error('请检查表单输入');
            return false;
        }
    });
};

// 重置表单
const onReset = () => {
    passwordForm.value.resetFields();
};

</script>
<style scoped>
.change-password-container {
    max-width: 500px;
    /* margin: 50px auto; */
    /* padding: 20px; */
    /* border: 1px solid #ebeef5; */
    border-radius: 4px;
    /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
}
</style>
